package com.fortune.cat.filter.factory;

import com.fortune.cat.filter.AbstractCustomizeGatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author zhaozeyang
 * @date 2019/4/4 13:06
 * @description customize GatewayFilter Uniform rules
 */
public abstract class AbstractCustomizeGatewayFilterFactory<T> extends AbstractGatewayFilterFactory<T> {

    public AbstractCustomizeGatewayFilterFactory(Class<T> configClass) {
        super(configClass);
    }

    @Override
    public String name() {
        return this.getClass().getSimpleName();
    }

    @Override
    public GatewayFilter apply(T config) {

        return new AbstractCustomizeGatewayFilter() {
            @Override
            public int getOrder() {
                return doGetOrder();
            }

            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                if (skipPresent(config, exchange)) {
                    return chain.filter(exchange);
                }
                return doApply(config, exchange, chain);
            }
        };
    }

    /**
     * 自定义过滤器来实现当前方法的功能
     *
     * @param config
     * @param exchange
     * @param chain
     * @return
     */
    protected abstract Mono<Void> doApply(T config, ServerWebExchange exchange, GatewayFilterChain chain);


    /**
     * 排序
     *
     * @return
     */
    protected abstract int doGetOrder();

    /**
     * 是否跳过当前过滤器
     *
     * @param t
     * @param exchange
     * @return
     */
    protected abstract boolean skipPresent(T t, ServerWebExchange exchange);
}
